package com.huilian.iotbox.data.utils;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;

/**
 * 图片操作合并工具
 *
 * @author chenqiwen
 * @CreateDate: 2022-08-19-15-22
 * @Description:
 */
public class ImageUtil {

    public static void main(String[] args) throws IOException {

        InputStream inputImage = new FileInputStream("F:\\2.jpg");
        BufferedImage sourceImage = ImageIO.read(inputImage);

        InputStream inputStream = ImageUtil.zoomSize(
                sourceImage,
                1080,
                500,
                true
        );

        System.out.println(inputStream);
    }

    /**
     * 字节图片转BufferedImage对象
     *
     * @param bytes
     * @return
     */
    public static BufferedImage bytesForMartBufferedImage(byte[] bytes) {
        Image image2Src = Toolkit.getDefaultToolkit().createImage(bytes);
        return BufferedImageBuilder.toBufferedImage(image2Src);
    }

    /**
     * 合并图片
     *
     * @param sourceUrl 图层
     * @param image2    加入合并的图片
     * @param x_offset  x轴偏移量，上或下
     * @param y_offset  y轴偏移量，左或右
     * @return
     * @throws IOException
     */
    public static InputStream mergedImages(String sourceUrl, BufferedImage image2, int x_offset, int y_offset) throws IOException {
        URL sourceFile = new URL(sourceUrl);


        Image image1Src = Toolkit.getDefaultToolkit().createImage(sourceFile);
        BufferedImage image = BufferedImageBuilder.toBufferedImage(image1Src);

//        // 方式1
//        Image image2Src = Toolkit.getDefaultToolkit().getImage("F:\\20220801101412.jpg");
//        // 方式2
//        Image image2Src = Toolkit.getDefaultToolkit().createImage(bytes);
//        BufferedImage image2 = BufferedImageBuilder.toBufferedImage(image2Src);

        System.out.println("imageWidth：" + image.getWidth());
        System.out.println("imageHeight：" + image.getHeight());
        System.out.println("image2Width：" + image2.getWidth());
        System.out.println("image2Height：" + image2.getHeight());
        image.setRGB(0, 0, BufferedImage.TYPE_3BYTE_BGR);
        image2.setRGB(0, 0, BufferedImage.TYPE_3BYTE_BGR);

        Graphics2D graphics2D = image.createGraphics();
        graphics2D.drawImage(
                image2,
                x_offset,
                y_offset,
                image2.getWidth(),
                image2.getHeight(),
                null
        );

        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
        ImageIO.write(image, "jpg", imOut);
        return new ByteArrayInputStream(bs.toByteArray());
    }

    /**
     * 比例缩放图片
     *
     * @param inputImage 原图片
     * @param width      期望宽：如1080
     * @param height     期望高：如1920
     * @param equalScale 是否等比例缩放
     */
    public static InputStream zoomSize(BufferedImage inputImage, int width, int height, boolean equalScale) {

        if (width < 0 || height < 0) {
            throw new RuntimeException("期望宽和期望高都不能为0");
        }

        System.out.println("srcImg size=" + inputImage.getWidth() + "X" + inputImage.getHeight());
        // targetW，targetH分别表示目标长和宽
        double sx = (double) width / inputImage.getWidth();
        double sy = (double) height / inputImage.getHeight();
        // 等比缩放
        if (equalScale) {
            if (sx > sy) {
                sx = sy;
                width = (int) (sx * inputImage.getWidth());
            } else {
                sy = sx;
                height = (int) (sy * inputImage.getHeight());
            }
        }
        System.out.println("destImg size=" + width + "X" + height);
        ColorModel cm = inputImage.getColorModel();
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();

        BufferedImage target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        Graphics2D graphics2D = target.createGraphics();


        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics2D.drawRenderedImage(inputImage, AffineTransform.getScaleInstance(sx, sy));
        graphics2D.dispose();
        // 将转换后的图片保存
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(target, "jpg", baos);
            return new ByteArrayInputStream(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static class BufferedImageBuilder {
        public static BufferedImage toBufferedImage(Image image) {
            if (image instanceof BufferedImage) {
                return (BufferedImage) image;
            }

            // 这段代码确保加载了图像中的所有像素
            image = new ImageIcon(image).getImage();

            BufferedImage bimage = null;

            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            try {
                int transparency = Transparency.OPAQUE;
                GraphicsDevice gs = ge.getDefaultScreenDevice();
                GraphicsConfiguration gc = gs.getDefaultConfiguration();
                bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);

            } catch (HeadlessException e) {
                //The system does not have a screen
            }
            if (bimage == null) {
                //Create a buffered image using the default color model
                int type = BufferedImage.TYPE_INT_RGB;
                bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
            }
            //Copy image to buffered image
            Graphics g = bimage.createGraphics();//Paint the image onto the buffered image
            g.drawImage(image, 0, 0, null);
            g.dispose();
            return bimage;
        }
    }
}
